﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LectorController.cs" company="">
//   Copyright (c) 2010/2011 All Right Reserved
// </copyright>
// <summary>
//   Contains LectorController class declaration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace IBupro.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using IBupro.Classes;
    using IBupro.Controllers.Classes;
    using IBupro.Models.Lector;
    using iBuproModel;
    using iBuproModel.Repositories.Interfaces;

    /// <summary>
    /// This controller contains actions related to role Lector.
    /// </summary>
    public class LectorController : CustomController
    {
        Entities context;
        IUserRepository userRepository;

        public LectorController()
        {
            if (this.context == null)
            {
                this.context = new Entities();
            }

            this.userRepository = this.repositoryService.UserRepositoryCreateInstance();
        }

        public ActionResult Index()
        {
            try
            {
                return View();
            }
            catch 
            {
                throw new Exception("Cannot list lectors");
            }
        }

        [Authorize(Roles = "Lector")]
        public ActionResult Disapprove(int id)
        {
            try
            {
                Project project = context.Projects.Where(p => p.Id == id).SingleOrDefault();
                List<OwnerRequest> requests = project.OwnerRequests.ToList();

                foreach (OwnerRequest request in requests)
                {
                    request.User = null;
                    request.Project = null;
                }

                OwnerRequest[] req = requests.ToArray();
                foreach (OwnerRequest t in req)
                {
                    this.context.OwnerRequests.DeleteObject(t);
                }

                ProjectSource[] sources = project.ProjectSources.ToArray();

                foreach (ProjectSource t in sources)
                {
                    t.Project = null;
                    this.context.ProjectSources.DeleteObject(t);
                }

                project.Users.Clear();
                project.Principal = null;


                this.context.Projects.DeleteObject(project);
                this.context.SaveChanges();
                
                return RedirectToAction("Notify", new { message = "Project " + project.Name + " has been disapproved" });
            }
            catch
            {
                throw new Exception("Cannot approve project");
            }
        }

        [Authorize(Roles = "Lector")]
        public ActionResult Approve(int id)
        {
            try
            {
                var project = this.context.Projects.Where(p => p.Id == id).SingleOrDefault();
                project.Approved = true;
                this.context.SaveChanges();
                FlashMessenger.AddMessage(Translator.Instance["projectApproved"], MessageType.Success);
                return RedirectToAction("Index");
            }
            catch
            {
                throw new Exception("Cannot approve project");
            }
        }

        public ActionResult Detail(int id)
        {
            iBuproModel.User user = this.userRepository.First(u => u.Id == id);
            if (this.userRepository.IsUserInRole(user, "Lector") == false)
            {
                throw new Exception("Requested user is not enrolled in lector service");
            }

            return View(user);
        }

        public ActionResult ListLectors()
        {
            IRoleRepository roles = repositoryService.RoleRepositoryCreateInstance();
            return View(roles.GetLectors());
        }

        /// <summary>
        /// Enrolls lector to subject
        /// </summary>
        /// <param name="id">id of lector</param>
        /// <returns></returns>
        [Authorize(Roles = "Admin, Principal")]
        public ActionResult EnrollToSubject(int id)
        {
            EnrollLectorToSubjectModel model = new EnrollLectorToSubjectModel();
            IUserRepository users = repositoryService.UserRepositoryCreateInstance();

            iBuproModel.User user = users.First(u => u.Id == id);

            model.Lector = user;
            model.ActualSubjects = user.LectorSubjects.Select(s => s.Id.ToString()).ToList();

            return View(model);
        }

        [Authorize(Roles = "Admin, Principal")]
        [HttpPost]
        public ActionResult EnrollToSubject(int id, EnrollLectorToSubjectModel model)
        {
            if (ModelState.IsValid)
            {
                IUserRepository users = repositoryService.UserRepositoryCreateInstance();
                iBuproModel.User user = users.First(u => u.Id == id);

                ISubjectRepository subjects = repositoryService.SubjectRepositoryCreateInstace();

                subjects.UpdateLectorSubjectList(user, model.SelectedSubjects);

                subjects.SaveChanges();

                FlashMessenger.AddMessage(Translator.Instance["lectorEnrolled"],MessageType.Success);

                return RedirectToAction("ListLectors", "Lector", null);
            }

            return View(model);
        }

        [ChildActionOnly]
        [Authorize(Roles = "Lector")]
        public ActionResult BookedDiplomProjects()
        {
            iBuproModel.User user = this.userRepository.GetUserByUserName(this.User.Identity.Name);
            IDiplomProjectStateRepository projectState = repositoryService.DiplomProjectStateRepositoryCreateInstance();

            return View(user.LectorDiplomProjects.Where(p => p.DiplomProjectState == projectState.GetBookedProjectState()));
        }

        [ChildActionOnly]
        [Authorize(Roles = "Lector")]
        public ActionResult LectorAcceptedDiplomProjects()
        {
            iBuproModel.User user = this.userRepository.GetUserByUserName(this.User.Identity.Name);
            IDiplomProjectStateRepository projectState = repositoryService.DiplomProjectStateRepositoryCreateInstance();

            return View(user.LectorDiplomProjects.Where(p => p.DiplomProjectState == projectState.GetLectorAcceptedProjectState()));
        }

        [ChildActionOnly]
        [Authorize(Roles = "Lector")]
        public ActionResult LectorSubscribedDiplomProjects()
        {
            iBuproModel.User user = this.userRepository.GetUserByUserName(this.User.Identity.Name);
            IDiplomProjectStateRepository projectState = repositoryService.DiplomProjectStateRepositoryCreateInstance();

            return View(user.LectorDiplomProjects.Where(p => p.DiplomProjectState == projectState.GetSubscribedProjectState()));
        }

        [ChildActionOnly]
        [Authorize(Roles = "Lector")]
        public ActionResult LectorNewDiplomProjects()
        {
            iBuproModel.User user = this.userRepository.GetUserByUserName(this.User.Identity.Name);
            IDiplomProjectStateRepository projectState = repositoryService.DiplomProjectStateRepositoryCreateInstance();

            return View(user.LectorDiplomProjects.Where(p => p.DiplomProjectState == projectState.GetNewProjectState()));
        }
    }
}
